﻿using Frame.Core.Common.Common;
using Frame.Core.Common.Configs;
using Frame.Core.Common.Dbs;
using Frame.Core.Common.Helpers;
using FreeSql;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Frame.Core.Extensions
{
    public static class DBServiceCollectionExtensions
    {
        /// <summary>
        /// 添加数据库
        /// </summary>
        /// <param name="services"></param>
        /// <param name="env"></param>
        public static void AddDbAsync(this IServiceCollection services, IHostEnvironment env)
        {
            services.AddScoped<UnitOfWorkManager>();
            var dbConfig = new ConfigHelper().Get<DbConfig>("dbconfig", env.EnvironmentName);

            #region FreeSql
            var freeSqlBuilder = new FreeSqlBuilder()
                    .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString)
                    .UseAutoSyncStructure(dbConfig.SyncStructure)
                    .UseLazyLoading(false)
                    .UseNoneCommandParameter(true);

            #region 监听所有命令
            if (dbConfig.MonitorCommand)
            {
                freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) =>
                {
                    //Console.WriteLine($"{cmd.CommandText}\n{traceLog}\r\n");
                    ConsoleHelper.WriteWarningLine($"{cmd.CommandText}\r\n");
                });

            }
            #endregion

            var fsql = freeSqlBuilder.Build();

            #region 监听Curd操作
            if (dbConfig.Curd)
            {
                fsql.Aop.CurdBefore += (s, e) =>
                {
                    ConsoleHelper.WriteSuccessLine($"{e.Sql}\r\n");
                };
            }
            #endregion

            services.AddSingleton(fsql);

            #endregion

            //导入多数据库
            if (null != dbConfig.Dbs)
            {
                foreach (var multiDb in dbConfig.Dbs)
                {

                    switch (multiDb.Name)
                    {
                        case nameof(MySqlDb):
                            var mdb = CreateMultiDbBuilder(multiDb).Build<MySqlDb>();
                            services.AddSingleton(mdb);
                            break;
                        default:
                            break;
                    }
                }
            }
        }

        /// <summary>
        /// 创建多数据库构建器
        /// </summary>
        /// <param name="multiDb"></param>
        /// <returns></returns>
        private static FreeSqlBuilder CreateMultiDbBuilder(MultiDb multiDb)
        {
            return new FreeSqlBuilder()
            .UseConnectionString(multiDb.Type, multiDb.ConnectionString)
            .UseAutoSyncStructure(false)
            .UseLazyLoading(false)
            .UseNoneCommandParameter(true);
        }
    }
}
